﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Threading;

namespace UDPChatClient
{
    public partial class UDPClient : Form
    {
        private UdpClient client;
        private IPEndPoint receivePoint;
        uint SequenceNumber = 0;
        const int HEADER_LENGHT = 8;

        public UDPClient()
        {
            InitializeComponent();

            // A hack to allow for cross thread messages - not for production use!
            Control.CheckForIllegalCrossThreadCalls = false;

            receivePoint = new IPEndPoint(new IPAddress(0), 0);
            client = new UdpClient(5001);
            Thread thread = new Thread(new ThreadStart(WaitForPackets));
            thread.Start();
        }

        // send a packet
        protected void inputTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                // create packet (datagram) as string
                string text = inputTextBox.Text;
                displayTextBox.Text += "\r\nSending packet containing: " + text;
                // convert packet to byte array

                byte[] packet = createPacket(System.Text.Encoding.ASCII.GetBytes(text));
                // send packet to server on port 5000
                client.Send( packet, packet.Length, "localhost", 5000 );
                displayTextBox.Text += "\r\nPacket sent\r\n";
                inputTextBox.Clear();
                displayTextBox.ScrollToCaret();
            }
        } // end method inputTextBox_KeyDown

      

        // wait for packets to arrive
        private void WaitForPackets()
        {
            while (true)
            {
                // receive byte array from server
                byte[] data = client.Receive(ref receivePoint);
                
                // output packet data to TextBox
                displayTextBox.Text += "\r\nPacket received:" +
                    "\r\nLength: " + data.Length + "\r\nContaining: " +
                    System.Text.Encoding.ASCII.GetString( data ) + "\r\n";
            }
        }

        // shut down the client
        private void UDPClient_FormClosing(object sender, FormClosingEventArgs e)
        {
            System.Environment.Exit(System.Environment.ExitCode);
        }

        private byte[] createPacket(byte[] payload)
        {
            byte[] packet = new byte[HEADER_LENGHT + payload.Length];
            Buffer.BlockCopy(System.Text.Encoding.ASCII.GetBytes("GAME"),0,packet,0,4);
            Buffer.BlockCopy(BitConverter.GetBytes(SequenceNumber++),0,packet,4,4);
            Buffer.BlockCopy(payload,0,packet,8,payload.Length);
            return packet;
        }
    }
}
